package ml;

import java.io.File;

import weka.core.Instances;
import weka.core.converters.ArffSaver;
import weka.core.converters.ConverterUtils.DataSource;
import weka.filters.Filter;

public class WekaUtil {

	public static Instances loadData(final String filename) throws Exception {
		return loadData(filename, true);
	}

	public static Instances loadData(final String filename,
			final boolean setClassIndex) throws Exception {
		System.out.println("Loading data from " + filename + " ...");

		final Instances data = new DataSource(filename).getDataSet();
		if (setClassIndex) {
			data.setClassIndex(data.numAttributes() - 1);
		}
		System.out.println("Loading data from " + filename + " finished.");
		return data;
	}

	public static void saveData(final Instances data, final String outputFile)
			throws Exception {
		System.out.println("Saving data to " + outputFile);
		final ArffSaver saver = new ArffSaver();
		saver.setInstances(data);
		saver.setFile(new File(outputFile));
		saver.writeBatch();
	}

	public static Instances filter(final Instances data, final Filter filter,
			final String msg) throws Exception {
		System.out.println(msg);
		filter.setInputFormat(data);
		return Filter.useFilter(data, filter);
	}
}
